package vno.fux.ui
{
	import fl.controls.Button;
	import fl.controls.List;
	
	import flash.display.DisplayObject;
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.events.TextEvent;
	import flash.filters.BlurFilter;
	import flash.filters.DropShadowFilter;
	import flash.filters.GlowFilter;
	import flash.filters.GradientBevelFilter;
	import flash.filters.GradientGlowFilter;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	
	import org.aswing.VectorListModel;
	import org.aswing.event.ListItemEvent;
	
	import vno.fux.BaseDisplayObject;
	import vno.fux.BasePoint;
	import vno.fux.CompassDirection;
	import vno.fux.ExPoint;
	import vno.fux.GlobalEventScheduler;
	import vno.fux.GlobalVar;
	import vno.fux.events.MapEvent;
	import vno.fux.events.NpcEvent;
	import vno.fux.mediator.LayerMediator;
	import vno.fux.move.MoveSystem;
	import vno.fux.res.pool.BitmapAttacher;
	import vno.fux.res.pool.ConfigPool;
	import vno.fux.res.pool.MapResource;
	import vno.fux.res.pool.MinimapResource;
	import vno.fux.res.pool.ResourcePool;
	import vno.fux.task.TaskSystem;
	import vno.ky.aswing.MyList;
	import vno.sci.event.MonologEvent;
	import vno.sci.mapEditor.BuildingBuoy;
	import vno.sci.mapEditor.BuildingInfo;
	import vno.sci.window.Monolog;
	import vno.sci.window.SimpleMessageBox;

	public class UiLayer extends Sprite
	{
		private var _walkTarget:WalkTarget;
		private var _isMod:Boolean = false;
		private var _modGround:Sprite;
		private var _minimap:Minimap;
		private var _taskSystem:TaskSystem;
		private var _mediator:LayerMediator;
		private var _buildingBuoy:BuildingBuoy;
		private var _fullMiniMap:Sprite;
		public function UiLayer()
		{
			//addChild(new SimpleMessageBox("", "Hello world"));
			_taskSystem = TaskSystem.getInstance();
			
			this.mouseEnabled = false;
			_walkTarget = new WalkTarget(0,0);
			GlobalEventScheduler.getInstance().addResizeListener(resizeHandler);
			_buildingBuoy = new BuildingBuoy(
				ConfigPool.getInstance().getBinaryData("m11building"), GlobalVar.stage.stageWidth, GlobalVar.stage.stageHeight);
			addChild(_buildingBuoy);
			addChild((new PicButton(1,1)).view);
			_minimap = new Minimap(3, 2);
			addChild(_minimap.view);
			_minimap.view.addEventListener(MapEvent.START_MOVE, needMove);
			initBuildingList();
			var bt:Button = new Button();
			bt.label = "About";
			bt.height = bt.height*1.5;
			bt.name = "CRbutton";
			bt.width = bt.width*1.5;
			bt.addEventListener(MouseEvent.CLICK, 
				function (event:Event):void
				{
					flash.net.navigateToURL(new URLRequest("about.html"), "_blank");
				}
			);
			//bt.graphics.beginFill(0xFFFFFF);
			//bt.graphics.drawRoundRect(0,0,bt.width,bt.height,5);
			//bt.graphics.endFill();
			bt.y = GlobalVar.stage.stageHeight - bt.height;
			bt.alpha = 1;
			this.addChild(bt);
			_fullMiniMap = new Sprite;
			var fullMiniMap:BitmapAttacher = new BitmapAttacher;
			(ResourcePool.getInstance().mapRes.getRes(11) as MapResource).thumbMap.attach(fullMiniMap);
			fullMiniMap.scaleX = 0.5;
			fullMiniMap.scaleY = 0.5;
			var sp:Sprite = new Sprite;
			sp.addChild(fullMiniMap);
			sp.addEventListener(MouseEvent.CLICK, fullMiniMapClickHandler);
			var mpMask:Sprite = new Sprite;
			mpMask.graphics.beginFill(0x000000);
			mpMask.graphics.drawRoundRect(0,0,fullMiniMap.width,fullMiniMap.height, 24);
			mpMask.graphics.endFill();

			_fullMiniMap.addChild(sp);
			_fullMiniMap.addChild(new Sprite);
			_fullMiniMap.addChild(new Sprite);
			_fullMiniMap.addChild(mpMask);
			_fullMiniMap.mask = mpMask;
			_fullMiniMap.alpha = 0.8;
			_fullMiniMap.filters = [new GlowFilter(0x999999,0.8,9,9,3)];
			_fullMiniMap.x = GlobalVar.stage.stageWidth/2 - _fullMiniMap.width/2;
			_fullMiniMap.y = GlobalVar.stage.stageHeight/2 - _fullMiniMap.height/2;
			GlobalVar.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler);
//			var list:Sprite = new Sprite;
//			var ml:MyList = new MyList(
//				{
//					"食堂":new VectorListModel(["1","2"]),
//					"宿舍":new VectorListModel(["1","2"])
//				}
//			);
//			list.addChild(ml);
//			list.graphics.beginFill(0xFFFFFF, 0.5);
//			list.graphics.drawRoundRect(0,0,ml.width,ml.height,10,10);
//			list.graphics.endFill();
//			addChild(list);
			//addChild(_walkTarget.view);
		}
		
		protected function fullMiniMapClickHandler(event:MouseEvent):void
		{
			needMove(new MapEvent(MapEvent.START_MOVE, {pos:new BasePoint(event.localX*20, event.localY*20)}));
		}
		
		protected function keyHandler(event:KeyboardEvent):void
		{
			if(event.keyCode == 77)
			{
				try
				{
					this.removeChild(_fullMiniMap);
				}
				catch(ae:ArgumentError)
				{
					if(_isMod) return;
					this.addChild(_fullMiniMap);
				}
			}
		}
		
		private function initBuildingList():void
		{
			var res:Object = {};
			var bi:Object = MoveSystem.getInstance().buildingAccessInfos;
			for(var key:String in bi)
			{
				var ar:Array = vector2array(Vector.<Object>(bi[key]));
				var vm:VectorListModel = new VectorListModel;
				vm.appendAll(ar);
				res[key] = vm;
			}
			var bl:MyList = new MyList(res);
			bl.name = "BuildingList";
			bl.x = GlobalVar.stage.stageWidth - bl.width -32;
			bl.y = 256;
			bl.addEventListener(ListItemEvent.ITEM_CLICK, listHandler);
			this.addChild(bl);
		}
		private function vector2array(vector_:Vector.<Object>):Array
		{
			var tmpAr:Array = [];
			for each(var i:Object in vector_)
			{
				tmpAr.push(i);
			}
			return tmpAr
		}
		protected function listHandler(event:ListItemEvent):void
		{
			var item:BuildingInfo = event.getValue() as BuildingInfo;
			needMove(new MapEvent(MapEvent.START_MOVE, {pos:new BasePoint(item.x, item.y)}));
		}
		
		protected function needMove(event:MapEvent):void
		{
			// TODO Auto-generated method stub
			//dispatchEvent(new MouseEvent(event.type,false,false,event.localX*10,event.localY*10));
			if(_isMod) return;
			dispatchEvent(event);
		}
		
		private function resizeHandler(event:Event):void
		{
			if(_isMod)
			{
				_modGround.width = GlobalVar.stage.stageWidth;
				_modGround.height = GlobalVar.stage.stageHeight;
			}
			_minimap.view.x = GlobalVar.stage.stageWidth -200;
			var bl:MyList = this.getChildByName("BuildingList") as MyList;
			bl.x = GlobalVar.stage.stageWidth - bl.width-32;
			
			_buildingBuoy.setRectSizeWH(stage.stageWidth, stage.stageHeight);
			
			var bt:Button = this.getChildByName("CRbutton") as Button;
			bt.y = GlobalVar.stage.stageHeight - bt.height; 
			
			var mapPos:BasePoint = this._mediator.getMapPos();
			_buildingBuoy.refresh(new ExPoint(mapPos.x - stage.stageWidth/2, mapPos.y - stage.stageHeight/2),
				new ExPoint(mapPos.x + stage.stageWidth/2, mapPos.y + stage.stageHeight/2));
			
			_fullMiniMap.x = GlobalVar.stage.stageWidth/2 - _fullMiniMap.width/2;
			_fullMiniMap.y = GlobalVar.stage.stageHeight/2 - _fullMiniMap.height/2;
		}
		
		public function handleNpcEvent(event:NpcEvent):void
		{
			var mapPos:BasePoint = this._mediator.getMapPos();
			if(event.pos.subtract2(mapPos).length > 192) return;
			_taskSystem.doTask(event.targetId);

		}
		
		public function setMod():void
		{
			if(_isMod)
				return;
			_modGround = new Sprite;
			_modGround.addEventListener(Event.REMOVED, releaseMod);
			_modGround.graphics.beginFill(0x999999);
			_modGround.graphics.drawRect(0, 0, GlobalVar.stage.stageWidth, GlobalVar.stage.stageHeight);
			_modGround.graphics.endFill();
			_modGround.alpha = 0.4;
			_modGround.mouseEnabled = true;
			addChildAt(_modGround, 0);
			_isMod = true;
		}
		
		private function releaseMod(event:Event):void
		{
			_isMod = false;
			_modGround.removeEventListener(Event.REMOVED, releaseMod);
		}
		public function unMod():void
		{
			_isMod = false;
			try
			{
				removeChild(_modGround);
			}
			catch(e:Error)
			{
				trace(e.message+e.getStackTrace());
			}
		}
		
		protected function windowCloseHandler(event:Event):void
		{
			var window:DisplayObject = event.target as DisplayObject;
			window.removeEventListener(TextEvent.LINK, linkHandler);
			this.removeChild(window);
			unMod();
			GlobalVar.stage.focus = null;
		}
		
		public function handleMapMove(event:MapEvent):void
		{
			_walkTarget.updatePos(event.pos);
			_minimap.handleMapMove(event);
			var fg:Graphics = (_fullMiniMap.getChildAt(1) as Sprite).graphics;
			//fg.clear();
			fg.beginFill(0xFF0000);
			fg.drawCircle(event.pos.x/20, event.pos.y/20, 1);
			fg.endFill();
			_buildingBuoy.refresh(new ExPoint(event.pos.x - stage.stageWidth/2, event.pos.y - stage.stageHeight/2),
				new ExPoint(event.pos.x + stage.stageWidth/2, event.pos.y + stage.stageHeight/2));
//			(_minimap.getChildAt(0) as Minimap).setCenter(new BasePoint(event.pos.x/10, event.pos.y/10));
		}
		public function handleMoveState(event:MapEvent):void
		{
			_walkTarget.moveStateHandle(event);
			var fg1:Graphics = (_fullMiniMap.getChildAt(1) as Sprite).graphics;
			var fg2:Graphics = (_fullMiniMap.getChildAt(2) as Sprite).graphics;
			switch(event.type)
			{
				case MapEvent.START_MOVE:
					addChildAt(_walkTarget.view, 0);
					fg1.clear();
					fg1.beginFill(0xFF0000);
					fg1.drawCircle(event.start.x/20, event.start.y/20, 3);
					fg1.endFill();
					//trace(event);
					fg2.clear();
					fg2.beginFill(0x0000FF);
					fg2.drawCircle(event.end.x/20, event.end.y/20, 3);
					fg2.endFill();
					break;
				case MapEvent.END_MOVE:
					removeChild(_walkTarget.view);
					//trace(event);
					fg1.clear();
					fg2.clear();
					fg1.beginFill(0xFF0000);
					fg1.drawCircle(event.pos.x/20, event.pos.y/20, 3);
					fg1.endFill();
					break;
				case MapEvent.UNREACH:
					addChildAt(_walkTarget.view, 0);
					break;
			}
		}

		public function get mediator():LayerMediator
		{
			return _mediator;
		}

		public function set mediator(value:LayerMediator):void
		{
			_mediator = value;
		}

		public function showWindow(content_:String):void
		{
			var window:MessageWindow = new MessageWindow (0,0,"", content_);
			window.view.addEventListener(vno.sci.event.MonologEvent.CLOSING, windowCloseHandler);
			window.view.addEventListener(TextEvent.LINK, linkHandler);
			setMod();
			addChild(window.view);
		}
		
		protected function linkHandler(event:TextEvent):void
		{
			var target:BuildingInfo = MoveSystem.getInstance().find(event.text);
			(event.currentTarget as EventDispatcher).dispatchEvent(new MonologEvent(0, vno.sci.event.MonologEvent.CLOSING));
			needMove(new MapEvent(MapEvent.START_MOVE, {pos:new BasePoint(target.x, target.y)}));
		}
	}
}